package cn.jekun.shop.common.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpCoupon;
import cn.jekun.component.core.service.gen.ErpCouponService;
import cn.jekun.shop.common.bean.CouponCount;

@Service(CouponService.BEAN_NAME)
public class CouponService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.CouponService";
	


	@Resource(name=ErpCouponService.BEAN_NAME)
	private ErpCouponService erpCouponService;
	
	@Override
	public String getNamespace() {
		return "SHOP_COUNPON";
	}
	
	/**
	 * 用户优惠券列表
	 * @param userId
	 * @param available
	 * @param page
	 * @return
	 */
	public JSONObject getCouponList(@Security String userId,@Security String available, Page page) {
		JSONObject jsonObject = new JSONObject();
		
		Map map = new HashMap();
		map.put(ErpCoupon.COL_USER_ID, userId);
		map.put(ErpCoupon.COL_AVAILABLE, available);
		SqlUtis.prepareSql(map
				,SqlUtis.getSQL(map, ErpCoupon.COL_USER_ID)
				,SqlUtis.getSQL(map, ErpCoupon.COL_AVAILABLE)
				,SqlUtis.orderBy(ErpCoupon.COL_CREATE_TIME)
				);
		List<ErpCoupon> list = this.erpCouponService.list(map , page);
		
		jsonObject.put("coupons", JSONArray.fromObject(list));
		
		jsonObject.put(Constants.Page.TOTAL_COUNT, page.getTotalCount());
		jsonObject.put(Constants.Page.TOTAL_PAGE, page.getPages());
		
		return this.executeRerutn(jsonObject);
	}

	/**
	 * 统计个人使用的红包金额
	 * @param userId
	 * @return
	 */
	public JSONObject countCoupons(@NotBlank(message="用户代码不能为空") String userId) {
		JSONObject jsonObject = new JSONObject();
		
		Map map = new HashMap();
		map.put("userId", userId);
		
		CouponCount couponCount = this.one(this.getStatementName("count"),map);
		
		jsonObject.put("total", couponCount.getTotal()==null?0:couponCount.getTotal());
		jsonObject.put("totalUnused", couponCount.getTotalUnused()==null?0:couponCount.getTotalUnused());
		jsonObject.put("totalUsed", couponCount.getTotalUsed()==null?0:couponCount.getTotalUsed());
		
		return this.executeRerutn(jsonObject);
	}

}
